const conn = require('../app/database')

class FileService {
  async createAvatar(filename, mimetype, size, userId) {
    const statement = `INSERT INTO avatar(filename, mimetype, size, user_id) VALUES (?,?,?,?);`
    const result = await conn.execute(statement, [filename, mimetype, size, userId])
    return result[0]
  }

  async getAvatarByUserId(userId) {
    const statement = `SELECT * FROM avatar WHERE user_id = ?;`
    const result = await conn.execute(statement, [userId])
    // 这里允许同一个用户有多张头像图片，获取的时候，我们将最新的图片返回出去
    return result[0].pop()
  }

  async createFile(filename, mimetype, size, momentId, id) {
    const statement = `INSERT INTO file(filename, mimetype, size, moment_id, user_id) VALUES (?,?,?,?,?);`
    const result = await conn.execute(statement, [filename, mimetype, size, momentId, id])
    return result[0]
  }

  async getPictureByFileName(filename) {
    const statement = `SELECT * FROM file WHERE filename = ?;`
    const result = await conn.execute(statement, [filename])
    return result[0]
  }
}

module.exports = new FileService()